package ru.spb.osll.myfit.server.handler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.Vector;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.Table;
import ru.spb.osll.myfit.common.TableStyle;
import ru.spb.osll.myfit.server.Converter;
import ru.spb.osll.myfit.server.ImportsPrinter;
import ru.spb.osll.myfit.server.log.Log;
import ru.spb.osll.myfit.server.parser.PageParser;
import ru.spb.osll.myfit.server.parser.PageParserUtils;
import ru.spb.osll.myfit.server.parser.RecursiveIncludeException;

/**
 * @author kdv
 * 
 */
public class ContentHandler implements Handler {
	protected PageParser m_parser = new PageParser(new Converter());
	private PageLoader m_pageLoader;
	private ImportsPrinter m_importsPrinter;

	public ContentHandler(ImportsPrinter importsPrinter, String root, PageLoader pageLoader) {
		m_importsPrinter = importsPrinter;
		m_pageLoader = pageLoader;
	}

	@Override
	public Table getTable(Vector<String> rawTable, TableStyle style) {
		Table table = m_parser.parseTable(rawTable);
		Log.log.debug("Style " + style);
		table.setStyle(style);
		return table;
	}

	void savePage(Page page, PrintStream ostream) throws IOException {
		m_importsPrinter.printImports(page, ostream);
		ostream.append(PageParserUtils.pageToString(page));
	}

	@Override
	public Page loadPage(String fileName, String pagePath, String includePath)
			throws IOException {
		return m_pageLoader.loadPage(fileName, pagePath, includePath);
	}

	public Page createInlcudePage(String includePath, List<String> allPath)
			throws RecursiveIncludeException, FileNotFoundException {
		return m_pageLoader.createInlcudePage(includePath, allPath);
	}
	
	public Page createPageWithError(String errorMessage) {
		return m_pageLoader.createPageWithError(errorMessage);
	}

	@Override
	public void savePage(String path, Page page) throws IOException {
		Log.log.info("Saving page, path: " + path);
		File file = new File(path);
		if (!file.exists()) {
			File dir = new File(file.getParent());
			dir.mkdirs();
			file.createNewFile();
		}

		FileOutputStream stream = null;
		try {
			stream = new FileOutputStream(file);
			savePage(page, new PrintStream(stream));
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}
}
